package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.AfterSalesMapper;
import aiku.numericalcontroloa.Model.Entity.AfterSales;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import aiku.numericalcontroloa.Model.Entity.AfterRecords;
import aiku.numericalcontroloa.Service.AfterRecordsService;
import aiku.numericalcontroloa.Mapper.AfterRecordsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
* @author 马
* @description 针对表【after_records】的数据库操作Service实现
* @createDate 2024-03-14 15:27:10
*/
@Service
public class AfterRecordsServiceImpl extends ServiceImpl<AfterRecordsMapper, AfterRecords>
    implements AfterRecordsService{
    @Autowired
    private AfterSalesMapper afterSalesMapper;
    @Autowired
    private AfterRecordsMapper afterRecordsMapper;

    /**
     * 添加交流记录
     * @param afterRecords
     * @return
     */
    @Override
    public Result addExchange(AfterRecords afterRecords) {
        //TODO 权限还未验证
        //查询是否有改售后id记录
        AfterSales afterSales = afterSalesMapper.selectById(afterRecords.getAfterSalesId());
        if (afterSales == null){
            return Result.error(201,"该售后id不存在");
        }
        //存在测直接存入
        afterSales.setServiceFrequency(afterSales.getServiceFrequency() + 1);
        afterRecords.setAfterTime(new Date());
        afterSalesMapper.updateById(afterSales);
        int i = afterRecordsMapper.insert(afterRecords);
        //添加之后需要修改交流次数
        return i >0 ? Result.success("添加成功") : Result.error(201,"添加失败");
    }

    /**
     * 通过派单id查询交流记录,通过时间排序
     * @param afterSalesId
     * @return
     */
    @Override
    public Result selectExchange(String afterSalesId) {
        //TODO 还未做权限验证
        //先查询是否有改派单id
        AfterSales afterSales = afterSalesMapper.selectById(afterSalesId);
        if (afterSales == null){
            return Result.error(201,"该售后id不存在");
        }
        //则查询交流记录,并且时间排序,时间越新的在前面
        LambdaQueryWrapper<AfterRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AfterRecords::getAfterSalesId, afterSalesId);
        queryWrapper.orderByDesc(AfterRecords::getAfterTime);

        List<AfterRecords> afterRecordsList = afterRecordsMapper.selectList(queryWrapper);
        return Result.success(afterRecordsList);
    }
}




